package com.unicom.office.func;

import com.unicom.office.dataitem.DataItem;
import com.unicom.office.dataitem.ListDataItem;
import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.type.ListTypeItem;
import com.unicom.office.type.TypeItem;
import com.unicom.office.unit.OfficeUnit;
import com.unicom.office.var.VarItem;

import java.util.ArrayList;
import java.util.List;

public class ForFunc extends FuncBase{
    private FuncBase body;
    private FuncBase listFunc;
    private VarItem itemName;
    private VarItem indexName;
    private TypeItem typeItem;

    public ForFunc(TypeItem typeItem) {
        this.typeItem = typeItem;
    }

    public void setBody(FuncBase body) {
        if(body.getType() != getType()) {
            throw new RuntimeException("类型错误");
        }
        this.body = body;
    }

    public void setList(FuncBase listFunc) {
        if(!(listFunc.getType() instanceof ListTypeItem)) {
            throw new RuntimeException("数据类型错误");
        }
        this.listFunc = listFunc;
    }

    public void setItemName(VarItem itemName) {
        this.itemName = itemName;
    }

    public void setIndexName(VarItem indexName) {
        this.indexName = indexName;
    }

    public Object run(OfficeRuntime officeRuntime) {
        ListDataItem list = (ListDataItem) listFunc.run(officeRuntime);

        List<Object> result = new ArrayList<Object>();

//        officeRuntime.in(itemName, null);
//        if(indexName != null) {
//            officeRuntime.in(indexName, null);
//        }
        for (int i = 0; i < list.getValue().size(); i++) {
            DataItem o = list.get(i);
            officeRuntime.set(itemName, o.getValue());
            officeRuntime.set(indexName, i);
            result.add(body.run(officeRuntime));
        }
//        officeRuntime.out(itemName);
//        if(indexName != null) {
//            officeRuntime.out(indexName);
//        }

        return result;
    }

    public void runForMatch(OfficeUnit unit, OfficeRuntime officeRuntime) {
        ListDataItem list = (ListDataItem) listFunc.run(officeRuntime);

//        officeRuntime.in(itemName, null);
//        if(indexName != null) {
//            officeRuntime.in(indexName, null);
//        }
        OfficeUnit next = unit;
        while (next != null){
            body.runForMatch(next, officeRuntime);
            list.add(officeRuntime.get(itemName).getValue());
            next.setMatched(true);
            next = next.getNext();
        }
//        officeRuntime.out(itemName);
//        if(indexName != null) {
//            officeRuntime.out(indexName);
//        }
    }

    public TypeItem getType() {
        return this.typeItem;
    }
}
